package com.diuse.outer.analyse.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.diuse.outer.executor.HttpHelper;
import javafx.stage.StageStyle;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

/**
 * Created by Administrator on 2015/11/24 0024.
 */
public class AmapHelper {
    private String location;

    public AmapHelper(String loc) {
        this.location = loc;
    }

    public LngLat get() throws UnsupportedEncodingException {
        String addressStr = "http://restapi.amap.com/v3/geocode/geo?key=7b38ad933a5883c8b4836e5cd29110e3&address=";
        String getAddress = HttpHelper.requestGet(addressStr + URLEncoder.encode(location, "UTF-8"));
        JSONObject object = JSONObject.parseObject(getAddress);
        JSONArray geocodes = object.getJSONArray("geocodes");
        if (geocodes.size() == 0) {
            System.out.println("not found");
        } else if (geocodes.size() == 1) {
            JSONObject trueAddress = geocodes.getJSONObject(0);
            String location = trueAddress.getString("location");
            String lngX = location.split(",")[0];
            String latY = location.split(",")[1];
            System.out.println("lngX is: " + lngX + "  latY is: " + latY );
            return new LngLat(Double.parseDouble(lngX), Double.parseDouble(latY));
        } else {
            System.out.println("more than one found");
        }

        return new LngLat(0,0);
    }
    public static void main(String[] args) throws UnsupportedEncodingException {
        new AmapHelper("浙江大学紫荆港校区").get();
    }

    public static class LngLat {
        private double lng;
        private double lat;
        public LngLat(double lng, double lat) {
            this.lng = lng;
            this.lat = lat;
        }

        public double getLat() {
            return lat;
        }

        public double getLng() {
            return lng;
        }
    }
}
